package com.cloud.message.controller;

import com.cloud.common.bean.ResultInfo;
import com.cloud.common.context.SessionContext;
import com.cloud.common.context.VersionContext;
import com.cloud.common.util.JsonUtils;
import com.cloud.message.constant.MessageLevelEnum;
import com.cloud.message.dto.MessageDTO;
import com.cloud.message.entity.MessageDelay;
import com.cloud.message.rocketmq.MQMessage;
import com.cloud.message.rocketmq.RocketMQSender;
import com.cloud.message.service.MessageDelayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.Optional;

/**
 * 消费接口
 */
@Slf4j
@RestController
public class MessageController {

    @Autowired
    private RocketMQSender rocketMQSender;

    @Autowired
    private MessageDelayService messageDelayService;

    /**
     * 发送消息
     *
     * @param messageDTO
     * @return ResultInfo
     */
    @PostMapping("/message/send")
    public ResultInfo<String> send(@Valid @RequestBody MessageDTO messageDTO) {
        if (messageDTO.getDelaySeconds() == 0) {
            MQMessage message = new MQMessage();
            BeanUtils.copyProperties(messageDTO, message);
            message.setUserVersion(VersionContext.get());
            message.setUserSession(getUserSession());
            if (rocketMQSender.sendMessage(message)) {
                return ResultInfo.success();
            }
        } else {
            MessageDelay messageDelay = new MessageDelay();
            BeanUtils.copyProperties(messageDTO, messageDelay);
            messageDelay.setLevel(MessageLevelEnum.Lower.name());
            messageDelay.setUserVersion(VersionContext.get());
            messageDelay.setUserSession(getUserSession());
            messageDelay.setCreateTime(new Date());
            messageDelayService.save(messageDelay);
            return ResultInfo.success();
        }
        return ResultInfo.failure();
    }

    private String getUserSession() {
        return Optional.ofNullable(SessionContext.get()).map(session -> JsonUtils.toJSONString(session)).orElse(null);
    }
}

